<template>
	<div class="success_page">
		<!-- 步骤进度条 -->
		<div class="steps_container">
			<div class="steps_wrapper">
				<div class="step_item completed">
					<div class="step_number">✓</div>
					<div class="step_label">参会信息</div>
				</div>
				<div class="step_line completed"></div>
				<div class="step_item completed">
					<div class="step_number">✓</div>
					<div class="step_label">订单支付</div>
				</div>
				<div class="step_line completed"></div>
				<div class="step_item completed">
					<div class="step_number">✓</div>
					<div class="step_label">完成</div>
				</div>
			</div>
		</div>

		<!-- 成功消息 -->
		<div class="success_content">
			<div class="success_icon">
				<svg viewBox="0 0 1024 1024" width="120" height="120">
					<path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64z m193.5 301.7l-210.6 292c-12.7 17.7-39 17.7-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z" fill="#52c41a"></path>
				</svg>
			</div>
			<h1 class="success_title">支付成功！</h1>
			<p class="success_message">您的报名已成功提交，我们会尽快处理</p>
			
			<div class="order_info">
				<div class="info_item">
					<span class="info_label">订单编号：</span>
					<span class="info_value">{{ orderNumber }}</span>
				</div>
				<div class="info_item">
					<span class="info_label">支付时间：</span>
					<span class="info_value">{{ paymentTime }}</span>
				</div>
			</div>

			<div class="action_buttons">
				<button class="btn btn_secondary" @click="goToHome">
					返回首页
				</button>
				<button class="btn btn_primary" @click="goToOrders">
					查看我的报名
				</button>
			</div>

			<!-- 通知状态卡片 -->
			<div class="notification_status">
				<div class="notification_item" :class="{ success: notificationStatus.email }">
					<div class="notification_icon">
						<span v-if="notificationStatus.email">✓</span>
						<span v-else class="loading">⏳</span>
					</div>
					<div class="notification_content">
						<div class="notification_title">邮件通知</div>
						<div class="notification_desc">
							{{ notificationStatus.email ? '确认邮件已发送' : '正在发送确认邮件...' }}
						</div>
					</div>
				</div>
				<div class="notification_item" :class="{ success: notificationStatus.sms }">
					<div class="notification_icon">
						<span v-if="notificationStatus.sms">✓</span>
						<span v-else class="loading">⏳</span>
					</div>
					<div class="notification_content">
						<div class="notification_title">短信通知</div>
						<div class="notification_desc">
							{{ notificationStatus.sms ? '短信已发送到手机' : '正在发送短信通知...' }}
						</div>
					</div>
				</div>
			</div>

			<div class="tips">
				<p v-if="notificationStatus.email && notificationStatus.sms">✅ 所有通知已成功发送</p>
				<p v-else>📧 我们正在向您发送确认信息，请稍候...</p>
				<p>📱 如有疑问，请联系会议组委会</p>
			</div>
		</div>
	</div>
</template>

<script>
export default {
	name: 'UserParticipationSuccess',
		data() {
			return {
				orderNumber: '',
				paymentTime: '',
				userParticipationId: '',
				notificationStatus: {
					email: false,
					sms: false
				},
				checkNotificationInterval: null,
				retryTimer: null
			}
		},
	methods: {
		goToHome() {
			this.$router.push('/');
		},
		goToOrders() {
			this.$router.push('/user/center');
		},
		async checkAndUpdatePaymentStatus(retryCount = 0, maxRetries = 3) {
			// 主动查询并更新支付状态（防止回调没有到达的情况）
			if (!this.orderNumber || !this.userParticipationId) {
				console.warn('订单号或用户参会ID缺失，无法查询支付状态');
				return false;
			}
			
			try {
				console.log(`[支付状态查询] 开始主动查询... (尝试 ${retryCount + 1}/${maxRetries + 1})`, {
					orderNumber: this.orderNumber,
					userParticipationId: this.userParticipationId
				});
				
				const json = await this.$get('~/api/payment/alipay/check_and_update?', {
					orderNumber: this.orderNumber,
					userParticipationId: this.userParticipationId
				});
				
				console.log('[支付状态查询] 响应结果:', json);
				
				// 检查返回格式：后端返回的是 {result: {success: true, ...}}
				if (json.result && json.result.success === true) {
					console.log('[支付状态查询] ✅ 支付状态更新成功:', json.result);
					this.$message.success('支付状态已确认');
					return true; // 查询成功，不需要重试
				} else if (json.error) {
					console.warn('[支付状态查询] ❌ 支付状态更新失败:', json.error.message || json.error);
					if (retryCount >= maxRetries) {
						this.$message.warning('支付状态查询失败: ' + (json.error.message || '未知错误'));
					}
					return false; // 返回false，让调用者决定是否重试
				} else {
					const message = json.result?.message || '订单尚未支付成功';
					console.warn('[支付状态查询] ⚠️ 支付状态更新失败或订单尚未支付:', message);
					
					// 如果是"订单尚未支付成功"，可能需要等待，但不在这里重试（由定时器处理）
					return false;
				}
			} catch (error) {
				console.error('[支付状态查询] ❌ 查询支付状态失败:', error);
				if (retryCount >= maxRetries) {
					console.error('[支付状态查询] 已达到最大重试次数，停止查询');
				}
				return false;
			}
		},
		async sendNotifications() {
			// 模拟邮件通知（立即发送）
			setTimeout(() => {
				this.notificationStatus.email = true;
			}, 1000);
			
			// 模拟短信通知（延迟发送）
			setTimeout(() => {
				this.notificationStatus.sms = true;
			}, 2000);
			
			// 如果有user_participation_id，可以调用后端API检查通知状态
			if (this.userParticipationId) {
				this.checkNotificationStatus();
			}
		},
		async checkNotificationStatus() {
			// 每2秒检查一次通知状态
			this.checkNotificationInterval = setInterval(async () => {
				try {
					const json = await this.$get(`~/api/user_participation/get_obj?user_participation_id=${this.userParticipationId}`);
					if (json.result && json.result.obj) {
						const obj = json.result.obj;
						// 根据后端返回的状态更新通知状态
						// 这里假设后端有email_sent和sms_sent字段
						if (obj.email_sent) {
							this.notificationStatus.email = true;
						}
						if (obj.sms_sent) {
							this.notificationStatus.sms = true;
						}
						
						// 如果所有通知都发送完成，停止检查
						if (this.notificationStatus.email && this.notificationStatus.sms) {
							clearInterval(this.checkNotificationInterval);
						}
					}
				} catch (error) {
					console.error('检查通知状态失败:', error);
				}
			}, 2000);
		}
	},
	mounted() {
		// 从路由参数获取订单信息
		this.orderNumber = this.$route.query.order_number || this.$route.query.orderNumber || '未知';
		this.userParticipationId = this.$route.query.user_participation_id || this.$route.query.userParticipationId || '';
		
		console.log('[支付成功页面] 初始化参数:', {
			order_number: this.orderNumber,
			user_participation_id: this.userParticipationId,
			fullQuery: this.$route.query,
			fullPath: this.$route.fullPath
		});
		
		// 如果参数缺失，尝试从URL中解析
		if ((!this.orderNumber || this.orderNumber === '未知') && window.location.search) {
			const urlParams = new URLSearchParams(window.location.search);
			this.orderNumber = urlParams.get('order_number') || urlParams.get('orderNumber') || this.orderNumber;
			this.userParticipationId = urlParams.get('user_participation_id') || urlParams.get('userParticipationId') || this.userParticipationId;
			console.log('[支付成功页面] 从URL解析参数:', {
				order_number: this.orderNumber,
				user_participation_id: this.userParticipationId
			});
		}
		
		// 获取当前时间
		const now = new Date();
		this.paymentTime = now.getFullYear() + '-' + 
						   String(now.getMonth() + 1).padStart(2, '0') + '-' + 
						   String(now.getDate()).padStart(2, '0') + ' ' + 
						   String(now.getHours()).padStart(2, '0') + ':' + 
						   String(now.getMinutes()).padStart(2, '0') + ':' + 
						   String(now.getSeconds()).padStart(2, '0');
		
		// 主动查询并更新支付状态（防止回调没有到达）
		if (this.orderNumber && this.orderNumber !== '未知' && this.userParticipationId) {
			console.log('[支付成功页面] 开始主动查询支付状态，订单号:', this.orderNumber, 'user_participation_id:', this.userParticipationId);
			
			// 立即执行第一次查询（支付完成后立即检查）
			// 然后每隔3秒重试，最多重试5次
			this.checkAndUpdatePaymentStatus(0, 5);
			
			// 设置定时器，每隔3秒重试一次
			let retryCount = 0;
			const maxRetries = 5;
			this.retryTimer = setInterval(() => {
				retryCount++;
				if (retryCount <= maxRetries) {
					console.log(`[支付成功页面] 第 ${retryCount} 次主动查询支付状态...`);
					this.checkAndUpdatePaymentStatus(retryCount, maxRetries).then(success => {
						if (success) {
							console.log('[支付成功页面] 支付状态已更新成功，停止重试');
							clearInterval(this.retryTimer);
						}
					});
				} else {
					clearInterval(this.retryTimer);
					console.log('[支付成功页面] 已达到最大重试次数，停止主动查询');
				}
			}, 3000);
		} else {
			console.error('[支付成功页面] 缺少必要参数，无法查询支付状态:', {
				orderNumber: this.orderNumber,
				userParticipationId: this.userParticipationId,
				query: this.$route.query
			});
			this.$message.warning('订单信息不完整，无法确认支付状态');
		}
		
		// 模拟发送通知并更新状态
		this.sendNotifications();
	},
	beforeDestroy() {
		if (this.checkNotificationInterval) {
			clearInterval(this.checkNotificationInterval);
		}
		if (this.retryTimer) {
			clearInterval(this.retryTimer);
		}
	}
}
</script>

<style scoped>
.success_page {
	min-height: 100vh;
	background: #f5f7fa;
	padding-bottom: 4rem;
}

/* 步骤条样式 */
.steps_container {
	background: white;
	padding: 2rem 0;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	margin-bottom: 3rem;
}

.steps_wrapper {
	max-width: 600px;
	margin: 0 auto;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.step_item {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 0.5rem;
}

.step_number {
	width: 40px;
	height: 40px;
	border-radius: 50%;
	border: 2px solid #52c41a;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: 600;
	background: #52c41a;
	color: white;
	font-size: 20px;
}

.step_label {
	font-size: 14px;
	color: #52c41a;
	font-weight: 600;
}

.step_line {
	flex: 1;
	height: 2px;
	background: #52c41a;
	margin: 0 1rem;
	margin-bottom: 1.5rem;
}

/* 成功内容 */
.success_content {
	max-width: 600px;
	margin: 0 auto;
	background: white;
	padding: 3rem 2rem;
	border-radius: 12px;
	box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
	text-align: center;
}

.success_icon {
	margin-bottom: 1.5rem;
	animation: scaleIn 0.5s ease-out;
}

@keyframes scaleIn {
	from {
		transform: scale(0);
		opacity: 0;
	}
	to {
		transform: scale(1);
		opacity: 1;
	}
}

.success_title {
	font-size: 32px;
	font-weight: 700;
	color: #52c41a;
	margin: 0 0 1rem 0;
}

.success_message {
	font-size: 16px;
	color: #666;
	margin: 0 0 2rem 0;
}

.order_info {
	background: #f8f9fa;
	padding: 1.5rem;
	border-radius: 8px;
	margin-bottom: 2rem;
}

.info_item {
	display: flex;
	justify-content: center;
	padding: 0.5rem 0;
	gap: 1rem;
}

.info_label {
	color: #666;
	font-size: 14px;
}

.info_value {
	color: #333;
	font-weight: 600;
	font-size: 14px;
}

.action_buttons {
	display: flex;
	gap: 1rem;
	justify-content: center;
	margin-bottom: 2rem;
}

.btn {
	padding: 0.75rem 2rem;
	border: none;
	border-radius: 50px;
	font-size: 16px;
	font-weight: 600;
	cursor: pointer;
	transition: all 0.3s ease;
}

.btn_secondary {
	background: white;
	color: #42b983;
	border: 2px solid #42b983;
}

.btn_secondary:hover {
	background: #f0fdf7;
}

.btn_primary {
	background: linear-gradient(135deg, #42b983 0%, #35a372 100%);
	color: white;
	box-shadow: 0 4px 12px rgba(66, 185, 131, 0.3);
}

.btn_primary:hover {
	transform: translateY(-2px);
	box-shadow: 0 6px 20px rgba(66, 185, 131, 0.4);
}

.tips {
	padding-top: 2rem;
	border-top: 1px solid #e0e0e0;
	color: #999;
	font-size: 14px;
	line-height: 2;
}

.tips p {
	margin: 0.5rem 0;
}

/* 通知状态卡片 */
.notification_status {
	margin-bottom: 2rem;
	display: flex;
	flex-direction: column;
	gap: 1rem;
}

.notification_item {
	display: flex;
	align-items: center;
	gap: 1rem;
	padding: 1rem;
	background: #f8f9fa;
	border-radius: 8px;
	transition: all 0.3s ease;
}

.notification_item.success {
	background: #f0fdf7;
	border: 1px solid #52c41a;
}

.notification_icon {
	width: 40px;
	height: 40px;
	border-radius: 50%;
	background: #e0e0e0;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 20px;
	color: #999;
	transition: all 0.3s ease;
}

.notification_item.success .notification_icon {
	background: #52c41a;
	color: white;
}

.notification_icon .loading {
	animation: spin 1s linear infinite;
}

@keyframes spin {
	from { transform: rotate(0deg); }
	to { transform: rotate(360deg); }
}

.notification_content {
	flex: 1;
}

.notification_title {
	font-size: 16px;
	font-weight: 600;
	color: #333;
	margin-bottom: 0.25rem;
}

.notification_desc {
	font-size: 14px;
	color: #666;
}

.notification_item.success .notification_desc {
	color: #52c41a;
}

/* 响应式设计 */
@media (max-width: 768px) {
	.success_content {
		margin: 0 1rem;
	}
	
	.action_buttons {
		flex-direction: column;
	}
	
	.btn {
		width: 100%;
	}
}
</style>


